package ooboo.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

import ooboo.Assets;
import ooboo.Authenticator;
import ooboo.ImageCache;

public class PostPanel extends JPanel
{
	private static final long serialVersionUID = 1l;
	
	private String screenName;
	private JTextArea tweetArea;
	private JScrollPane scrollPane;
	private JLabel countLabel;
	private Image image;
	private boolean reply;
	private long replyToStatusID;
	private String replyToScreenName;
	private boolean shorten = false;
	private List<PostListener> listeners;
	
	public PostPanel()
	{
		this("",false,-1,"");
	}
	
	public PostPanel(String screenName,boolean reply,long replyToStatusID,String replyToScreenName)
	{
		this.screenName = screenName;
		this.reply = reply;
		this.replyToStatusID = replyToStatusID;
		this.replyToScreenName = replyToScreenName;
		image = ImageCache.getImage(screenName);
		
		listeners = new LinkedList<PostListener>();
		
		countLabel = new JLabel("140",reply?SwingConstants.LEFT:SwingConstants.RIGHT);
		countLabel.setBackground(Color.WHITE);
		countLabel.setFont(Assets.USER_FONT);
		add(countLabel);
		
		tweetArea = new JTextArea();
		//tweetArea.setFont(reply?REPLY_FONT:TEXT_FONT);
		tweetArea.getDocument().addDocumentListener(
				new DocumentListener()
				{
					public void changedUpdate(DocumentEvent e){}
					
					public void insertUpdate(DocumentEvent e)
					{
						updateCount();
					}
			
					public void removeUpdate(DocumentEvent e)
					{
						updateCount();
					}
				});
		if(reply)
			tweetArea.setText("@" + replyToScreenName + " ");
		tweetArea.setBorder(null);
		tweetArea.setFont(Assets.TEXT_FONT);
		tweetArea.setLineWrap(true);
		tweetArea.setOpaque(false);
		tweetArea.setWrapStyleWord(true);
		tweetArea.requestFocus();
		tweetArea.addKeyListener(
				new KeyAdapter()
				{
					public void keyReleased(KeyEvent e)
					{
						if(e.getKeyCode() == KeyEvent.VK_ENTER)
						{
							PostEvent event = new PostEvent(PostPanel.this.screenName,tweetArea.getText(),PostPanel.this.reply?PostPanel.this.replyToStatusID:-1);
							for(PostListener listener:listeners)
								listener.postSent(event);
							
							//Authenticator.getTweets(PostPanel.this.screenName);
							//System.out.println(tweetArea.getText());
							tweetArea.setText("");
						} else if (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_V) {
							shortenURLs();
							//tweetArea.setText(tweetArea.getText().trim());
						}
					}
				});
		
		scrollPane = new JScrollPane(tweetArea);
		scrollPane.getViewport().setOpaque(false);
		scrollPane.setBorder(null);
		scrollPane.setOpaque(false);
		scrollPane.setViewportBorder(null);
		add(scrollPane);
		addComponentListener(
				new ComponentAdapter()
				{
					public void componentResized(ComponentEvent e)
					{
						calcBounds();
					}
				});

		if(reply)
			setOpaque(false);
		else
			setBackground(Color.GRAY);
		setLayout(null);
		setPreferredSize(new Dimension(0,96));
	}
	
	public void addPostListener(PostListener listener)
	{
		listeners.add(listener);
	}
	
	public void removePostListener(PostListener listener)
	{
		listeners.remove(listener);
	}
	
	public void setScreenName(String screenName)
	{
		this.screenName = screenName;
		image = ImageCache.getImage(screenName);
		repaint();
	}
	
	public void validate()
	{
		super.validate();
		
		calcBounds();
	}
	
	private void calcBounds()
	{
		//*
		scrollPane.setBounds(80,getFontMetrics(Assets.USER_FONT).getHeight() + 13,
				reply?getWidth() - 157:getWidth() - 93,54);
		countLabel.setBounds(reply?74:getWidth() - 34,2,26,16);
		/*/
		scrollPane.setBounds(82,getFontMetrics(USER_FONT).getHeight() + 20,
				reply?getWidth() - 157:getWidth() - 93,50);
		countLabel.setBounds(reply?74:getWidth() - 34,2,26,16);
		//*/
	}
	
	private void updateCount()
	{
		int count = 140 - tweetArea.getDocument().getLength();
		countLabel.setText(Integer.toString(count));
		if(count <= 10)
			countLabel.setForeground(Color.RED);
		else
			countLabel.setForeground(Color.BLACK);
	}
	
	private void shortenURLs()
	{
		String postText = "";
		try {
			postText = tweetArea.getDocument().getText(0, tweetArea.getDocument().getLength());
		} catch (BadLocationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Pattern urlPattern = Pattern.compile("((https?):((//)|(\\\\))+[a-zA-Z:#@%/;$()~_?\\+-=\\.&]*[a-zA-Z0-9\\/)])");
		Matcher m = urlPattern.matcher(postText);
		
		while(m.find())
		{
			String url = postText.substring(m.start(), m.end());
			String shortenedURL = "";
			int start = m.start();
			int end = m.end();
			
			if (postText.substring(end-1, end).equals(")") && postText.substring(start-1, start).equals("(")) {
				end--;
			}
			
			if (url.length() > 20) {
				try {
					shortenedURL = Assets.getShortURL(url);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				tweetArea.replaceRange(shortenedURL, start, end);
				//newPostText = postText.replace(url, shortenedURL);
			}
		}
		
		//return newPostText;
	}
	
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		
		Graphics2D g2 = (Graphics2D)g;
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
		
		//ImageIcon background = new ImageIcon ("images/PostBackground.png");
		
		//for (int i = 0; i < 100; i++) {
			//g2.drawImage(background.getImage(), 0, 0, this.getWidth(), this.getHeight(), 0, 0, 18, 300, this);
		//}
		
		
		g2.setFont(Assets.USER_FONT);
		FontMetrics fm = g2.getFontMetrics(Assets.USER_FONT);
		int userHeight = fm.getHeight();

		g2.setColor(Color.BLACK);
		if(reply)
			g2.drawString(screenName,getWidth() - fm.stringWidth(screenName) - 74,userHeight);
		else
			g2.drawString("What are you doing?",4,userHeight);
		
		g2.drawImage(image,reply?getWidth() - 56:4,reply?8:(userHeight + 4),48,48,this);
		
		
		if(reply)
			Bubble.drawReply(Bubble.BLUE,g2,userHeight + 4,getWidth() - 58,
					userHeight + 79,64);
		else
			Bubble.drawBubble(Bubble.BLUE,g2,userHeight + 4,getWidth() - 5,
					userHeight + 75,54);
		/*else
			Bubble.drawBubble(Bubble.BLUE,g2,userHeight,getWidth(),
					userHeight + 79,60);*/
	}
}
